package com.mes.schedule.manager.ScheduleOperation;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.mes.common.util.Page;
import com.mes.common.util.SysUtil;
import com.mes.schedule.ScheduleOperation.dao.OperationCombineBatchDao;
import com.mes.schedule.algorithm.ScheduleStateFind;
import com.mes.schedule.domain.SOperationTask;
import com.mes.schedule.domain.SPartTask;
import com.mes.schedule.domain.ScheduleEvent;
import com.mes.schedule.domain.ScheduleOperationRecord;
import com.mes.schedule.domain.ScheduleScheme;
import com.mes.schedule.manager.ScheduleSchemeManager;
import com.mes.schedule.manager.iface.ScheduleOperation.IOperationCombineBatchManager;
import com.mes.common.exception.bo.BaseBusinessException;
import com.mes.common.exception.db.BaseDBException;
import com.mes.common.manager.BasicManager;
import com.mes.common.spring.SpringUtils;
import com.mes.common.util.IdentityGenerator;

/**
 * 最终应该由java消息系统来决替代，而不是数据库
 * 
 * @author AutoGenerateJavaTool 1.0
 * 
 */
@Component("operationCombineBatchManager")
@Transactional
public class OperationCombineBatchManager extends BasicManager implements IOperationCombineBatchManager{
	// private ScheduleEventDao scheduleEventDao;
	private OperationCombineBatchDao operationCombineBatchDao;
	// @Autowired
	private ScheduleStateFind scheduleStateFind = new ScheduleStateFind();

	 
	public void SaveOrUpdateBySource(String masterShopUid,
			ScheduleEvent scheduleEvent) throws BaseBusinessException {
		// ScheduleSchemeManager scheduleSchemeManager = SpringUtils
		// .getBean("schemeManager");
		// Set<String> schemeUidSet = scheduleSchemeManager
		// .getSchemeUidSet(masterShopUid);
		// if (schemeUidSet == null) {
		// return;
		// }
		//
		// try {
		//
		// for (String scheduleUid : schemeUidSet) {
		// scheduleEvent.setScheduleUid(scheduleUid);
		// ScheduleEvent oldScheduleEvent = scheduleEventDao
		// .getUnHandleEvent(scheduleEvent);
		// if (oldScheduleEvent == null) {
		// this.add(scheduleEvent);
		// } else {
		// String eventUid = oldScheduleEvent.getScheduleEventUid();
		// ObjectOperation.copyAttributes(scheduleEvent,
		// oldScheduleEvent);
		// oldScheduleEvent.setScheduleEventUid(eventUid);
		// this.update(oldScheduleEvent);
		// }
		// }
		// } catch (BaseDBException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// throw new BaseBusinessException(e.getMessage());
		// }

	}

	 
	public void addScheduleEvent(String masterShopUid,
			ScheduleEvent scheduleEvent) throws Exception {
		ScheduleSchemeManager scheduleSchemeManager = SpringUtils
				.getBean("schemeManager");
		Set<String> schemeUidSet = scheduleSchemeManager
				.getSchemeUidSet(masterShopUid);
		if (schemeUidSet == null) {
			return;
		}

		try {

			for (String scheduleUid : schemeUidSet) {
				//
				try {
					// 要clone,否则add之后就会变成hibermate持久态，认为是一个对象
					ScheduleEvent e = (ScheduleEvent) scheduleEvent.clone();
					e.setScheduleUid(scheduleUid);
					this.add(e);
				} catch (CloneNotSupportedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		} catch (BaseDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseBusinessException(e.getMessage());
		}

	}

	public void writeOperLog(ScheduleScheme scheme, String eventType,
			Element operElement) throws Exception {

		// 写日志
		ScheduleEvent scheduleEvent = new ScheduleEvent();
		scheduleEvent.setScheduleUid(scheme.getScheduleUid());
		scheduleEvent.setEventType(eventType);
		// scheduleEvent.setKeyUid(keyUid);
		Format format = Format.getCompactFormat();
		format.setEncoding("UTF-8");
		format.setIndent("  ");
		XMLOutputter outputter = new XMLOutputter(format);
		scheduleEvent.setEventContent(outputter.outputString(operElement));

		scheduleEvent.setEventState(ScheduleEvent.EVENTSTATE_SUCCESS);
		scheduleEvent.setSourceUid(scheme.getScheduleUid());
		scheduleEvent.setCreatorUid(SysUtil.getSessionEmployeeUid());
		scheduleEvent.setCreateTime(new Date());
		String str = "";
		try {
			SAXBuilder sb = new SAXBuilder(false);
			String strXml = scheduleEvent.getEventContent();
			StringReader read = new StringReader(strXml);
			Document doc = sb.build(read);
			if (eventType.equals(ScheduleEvent.EVENTTYPE_PARTTASK_PLANINFO)) {
				str = scheduleStateFind.eventProPartTaskPlanInfoChange(scheme,
						scheduleEvent, doc);
			} else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_PARTTASK_SPLITBATCH))
				str = scheduleStateFind.eventProPartTaskSplitBatch(scheme,
						scheduleEvent, doc);
			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_PLANINFO))
				str = scheduleStateFind.eventProOperationPlanInfo(scheme,
						scheduleEvent, doc);
			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_PARTTASK_COMBINEBATCH))
				str = scheduleStateFind.eventProPartTaskCombineBatch(scheme,
						scheduleEvent, doc);
			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_PARTTASK_CANCELCOMBINEBATCH))
				str = scheduleStateFind.eventProPartTaskCancelCombineBatch(
						scheme, scheduleEvent, doc);
			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_GROUP))
				str = scheduleStateFind.eventProOperationTaskGroup(scheme,
						scheduleEvent, doc);

			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_CANCELGROUP))
				str = scheduleStateFind.eventProOperationTaskCancelGroup(
						scheme, scheduleEvent, doc);

			else if (eventType.equals(ScheduleEvent.EVENTTYPE_PARTTASK_ADD))
				str = scheduleStateFind.eventProPartTaskAdd(scheme,
						scheduleEvent, doc);

			else if (eventType.equals(ScheduleEvent.EVENTTYPE_PARTTASK_DELETE))
				str = scheduleStateFind.eventProPartTaskDELETE(scheme,
						scheduleEvent, doc);

			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_ADD))
				str = scheduleStateFind.eventProOperationTaskAdd(scheme,
						scheduleEvent, doc);

			else if (eventType
					.equals(ScheduleEvent.EVENTTYPE_OPERATIONTASK_DELETE))
				str = scheduleStateFind.eventProOperationTaskDELETE(scheme,
						scheduleEvent, doc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		scheduleEvent.setEventDesc(str);
		this.add(scheduleEvent);
	}

	 
	public List<String> getEventChildPara(ScheduleEvent scheduleEvent,
			String eventPara, ScheduleScheme scheme) throws Exception {
		List<String> paraValueStringList = new ArrayList<String>();
		SAXBuilder sb = new SAXBuilder(false);
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		BeanUtils beanUtils = new BeanUtils();
		String strXml = scheduleEvent.getEventContent();
		StringReader read = new StringReader(strXml);
		Document doc = sb.build(read);
		String eventType = scheduleEvent.getEventType();
		Element rootElement = doc.getRootElement();
		List<Element> elements = rootElement.getChildren();
		List<SPartTask> partTasks = new ArrayList<SPartTask>();
		for (Element elem : elements) {
			String paraValueString = elem.getAttributeValue(eventPara);
			if (paraValueString != null && !"".equals(paraValueString)) {
				paraValueStringList.add(paraValueString);
			}
		}
		return paraValueStringList;
	}

	 
	public String getEventPara(ScheduleEvent scheduleEvent, String eventPara,
			ScheduleScheme scheme) throws Exception {
		String paraValueString = "";
		SAXBuilder sb = new SAXBuilder(false);
		SimpleDateFormat formatDate = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		BeanUtils beanUtils = new BeanUtils();
		String strXml = scheduleEvent.getEventContent();
		StringReader read = new StringReader(strXml);
		Document doc = sb.build(read);
		String eventType = scheduleEvent.getEventType();
		Element rootElement = doc.getRootElement();
		paraValueString = rootElement.getAttributeValue(eventPara);
		return paraValueString;
	}

	 
	public List<ScheduleOperationRecord> findScheduleEventsByConditions(
			ScheduleScheme scheme, String keyUid, Date fromDate, Date toDate,
			Integer eventState, String eventType, String eventObject,
			String drawingId, String batchNum, Page page) throws Exception {
		return null;
	}


	 
	public void createCombineBatchInfo(List<SPartTask> updatedPartList,
			List<SOperationTask> CombinedOperationsList) throws Exception {
		if (updatedPartList == null || CombinedOperationsList == null) {
			return;
		}
		for (SPartTask partTask : updatedPartList) {
			ScheduleOperationRecord record = new ScheduleOperationRecord();
			record.setScheduleOperationUid(IdentityGenerator
					.GetIdentityString());
			record.setDrawingId(partTask.getDrawingId());
			record.setBatchNum(partTask.getBatchNum());
			record.setScheduleUid(partTask.getScheduleUid());
			record.setEventState(1);
			record.setParentUid(null);
			record.setCreateTime(new Date());
			record
					.setEventType(ScheduleOperationRecord.EVENTTYPE_PARTTASK_SPLITBATCH);
			this.add(record);
		}

		// TODO Auto-generated method stub

	}

	public OperationCombineBatchDao getOperationCombineBatchDao() {
		return operationCombineBatchDao;
	}

	public void setOperationCombineBatchDao(
			OperationCombineBatchDao operationCombineBatchDao) {
		this.operationCombineBatchDao = operationCombineBatchDao;
	}

}
